#!/bin/sh

# This script assembles the RYMOS bootloader, kernel and programs
# with NASM, and then creates floppy and CD images (on Linux)

# Only the root user can mount the floppy disk image as a virtual
# drive (loopback mounting), in order to copy across the files

# (If you need to blank the floppy image: 'mkdosfs disk_images/robertos.flp')


if test "`whoami`" != "root" ; then
	echo "You must be logged in as root to build (for loopback mounting)"
	echo "Enter 'su' or 'sudo bash' to switch to root"
	exit
fi


if [ ! -e img/rymos.flp ]
then
	echo ">>> Creating new RYMOS floppy image..."
	#mkdosfs -C img/rymos.flp 1440 || exit
	cp img/grub.img img/rymos.flp
else
	rm img/rymos.flp
	echo ">>> Creating new RYMOS floppy image..."
	#mkdosfs -C img/rymos.flp 1440 || exit
	cp img/grub.img img/rymos.flp

fi

if [ ! -e img/rymos2.flp ]
then
	echo ">>> Creating new RYMOS GRUB2 floppy image..."
	#mkdosfs -C img/rymos.flp 1440 || exit
	cp img/grub2.img img/rymos2.flp
else
	rm img/rymos2.flp
	echo ">>> Creating new RYMOS GRUB2 floppy image..."
	#mkdosfs -C img/rymos.flp 1440 || exit
	cp img/grub2.img img/rymos2.flp

fi

echo ">>> Compiling RYMOS libs..."

cd libs
make
cd ..


echo ">>> Compiling RYMOS kernel..."

cd kernel
make
cd ..


echo ">>> Making initrd..."

cd initrd
make clean
make
make pack
cd ..


#echo ">>> Adding bootloader to floppy image..."

#dd status=noxfer conv=notrunc if=bootload/bootload.bin of=img/rymos.flp || exit

echo ">>> Mounting loopback floppy..."
rm -rf tmp-loop
mkdir tmp-loop && mount -o loop -t vfat img/rymos.flp tmp-loop
rm -rf tmp-loop2
mkdir tmp-loop2 && mount -o loop -t vfat img/rymos2.flp tmp-loop2

echo ">>> Copying Grub Menu..."
cp img/menu.lst tmp-loop/boot/grub/
cp img/grub.cfg tmp-loop2/boot/grub/

echo ">>> Copying initrd..."
cp initrd/initrd tmp-loop/
cp initrd/initrd tmp-loop2/

echo ">>> Copying RYMOS kernel and programs..."

cp kernel/kernel.rsf tmp-loop/
cp kernel/kernel.rsf tmp-loop2/

mkdir tmp-loop/D1
mkdir tmp-loop/D1/D12
mkdir tmp-loop/D2
mkdir tmp-loop/D3

echo 'Arch Linux' > tmp-loop/D1/D12/Arch.txt
echo 'RYMOS' > tmp-loop/D3/RYMOS.TXT

sleep 1.2

echo ">>> Unmounting loopback floppy..."

umount tmp-loop || exit
umount tmp-loop2 || exit

rm -rf tmp-loop
rm -rf tmp-loop2

echo ">>> Creating CD-ROM ISO image..."

rm -f img/rymos.iso
mkisofs -quiet -V 'RYMOS' -input-charset iso8859-1 -o img/rymos.iso -b rymos.flp img/ || exit

echo ">>> Setting folder and files permisions..."
sudo chmod ugoa+rw -R ../rymos

echo '>>> Done!'

